<?php
namespace Easy\Db;

class DbDriver{
	
	// 数据库类型
	protected $dbType     = null;
	// 是否自动释放查询结果
	protected $autoFree   = false;
	// 当前操作所属的模型名
	protected $model      = '_easy_';
	// 是否使用永久连接
	protected $pconnect   = false;
	// 当前SQL指令
	protected $queryStr   = '';
	protected $modelSql   = array();
	// 最后插入ID
	protected $lastInsID  = null;
	// 返回或者影响记录数
	protected $numRows    = 0;
	// 返回字段数
	protected $numCols    = 0;
	// 事务指令数
	protected $transTimes = 0;
	// 错误信息
	protected $error      = '';
	// 数据库连接ID 支持多个连接
	protected $linkID     = array();
	// 当前连接ID
	protected $_linkID    = null;
	// 当前查询ID
	protected $queryID    = null;
	// 是否已经连接数据库
	protected $connected  = false;
	// 数据库连接参数配置
	protected $config     = '';
	// 数据库表达式
	protected $comparison = array('eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN');
	// 查询表达式
	protected $selectSql  = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%COMMENT%';
	//更新表达式
	protected $updateSql  =	 'UPDATE %TABLE% %SET% %WHERE% %LIMIT% %COMMENT%';
	//删除表达式
	protected $deleteSql  =	 'DELETE FROM %TABLE% %WHERE% %LIMIT% %COMMENT%';
	// 参数绑定
	protected $bind       = array();
	
	/**
	 * 取得数据库类实例
	 * @static
	 * @access public
	 * @return mixed 返回数据库驱动类
	 */
	public static function getInstance($db_config='') {
		static $_instance	=	array();
		$guid	=	to_guid_string($db_config);
		if(!isset($_instance[$guid])){
			$_instance[$guid]	=	self::factory($db_config);
		}
		return $_instance[$guid];
	}
	
	/**
	 * 加载数据库 支持配置文件或者 DSN
	 * @access public
	 * @param mixed $db_config 数据库配置信息
	 * @return string
	 */
	private static function factory($db_config='') {
		// 读取数据库配置
		$db_config = self::parseConfig($db_config);
		// 数据库类型
		$dbType =   ucwords(strtolower($db_config['dbms']));
		$class  =   'Easy\\Db\\Driver\\'. $dbType;
		// 检查驱动类
		if(class_exists($class)) {
			$db = new $class($db_config);
		}else {
			// 类没有定义
			E('_NO_DB_DRIVER_: ' . $class);
		}
		return $db;
	}
	
	/**
	 * 分析数据库配置信息，支持数组和DSN
	 * @access private
	 * @param mixed $db_config 数据库配置信息
	 * @return string
	 */
	private static function parseConfig($db_config='') {
		if(empty($db_config) || !is_array($db_config)){
			E('db_config_not_null');
		}
		$db_config = array(
				'dbms'      =>  isset($db_config['dbms'])?$db_config['dbms']:'Pdo',
				'username'  =>  $db_config['dbuser'],
				'password'  =>  $db_config['dbpwd'],
				'masterhost'=>  $db_config['master_host'],
				'slavehost'	=> 	$db_config['slave_host'],
				'hostport'  =>  isset($db_config['db_port'])?$db_config['db_port']:3306,
				'database'  =>  $db_config['dbname'],
				'charset'   =>  isset($db_config['db_charset'])?$db_config['db_charset']:'utf8',
		);
		return $db_config;
	}
	
	/**
	 * 参数绑定
	 * @access protected
	 * @param string $name 绑定参数名
	 * @param mixed $value 绑定值
	 * @return void
	 */
	protected function bindParam($name,$value){
		if(isset($this->bind[':'.$name])){
			$name = md5($name);
		}
		$this->bind[':'.$name]  =   $value;
		return $name;
	}
	
	/**
	 * SQL指令安全过滤
	 * @access public
	 * @param string $str  SQL字符串
	 * @return string
	 */
	public function escapeString($str) {
		if($this->_linkID) {
			return mysql_real_escape_string($str,$this->_linkID);
		}else{
			return mysql_escape_string($str);
		}	
	}
	
	/**
	 * 设置锁机制
	 * @access protected
	 * @return string
	 */
	protected function parseLock($lock=false) {
		if(!$lock) return '';
		if('ORACLE' == $this->dbType) {
			return ' FOR UPDATE NOWAIT ';
		}
		return ' FOR UPDATE ';
	}
	
	/**
	 * set分析
	 * @access protected
	 * @param array $data
	 * @return string
	 */
	protected function parseSet($data) {
		if(empty($data)) return '';
		foreach ($data as $key=>$val){
			if(is_array($val) && 'exp' == $val[0]){
				$set[]  =   $this->parseKey($key).'='.$val[1];
			}elseif(is_scalar($val) || is_null($val)) { // 过滤非标量数据
				$name   =   md5($key);
				$name = $this->bindParam($name,$val);
				$set[]  =   $this->parseKey($key).'=:'.$name;
			}
		}
		return ' SET '.implode(',',$set);
	}
	
	/**
	 * 参数绑定分析
	 * @access protected
	 * @param array $bind
	 * @return array
	 */
	protected function parseBind($bind){
		$bind           =   array_merge($this->bind,$bind);
		$this->bind     =   array();
		return $bind;
	}
	
	/**
	 * 字段名分析
	 * @access protected
	 * @param string $key
	 * @return string
	 */
	protected function parseKey(&$key) {
		return $key;
	}
	
	/**
	 * value分析
	 * @access protected
	 * @param mixed $value
	 * @return string
	 */
	protected function parseValue($value) {
		if(is_string($value)) {
			$value =  '\''.$this->escapeString($value).'\'';
		}elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
			$value =  $this->escapeString($value[1]);
		}elseif(is_array($value)) {
			$value =  array_map(array($this, 'parseValue'),$value);
		}elseif(is_bool($value)){
			$value =  $value ? '1' : '0';
		}elseif(is_null($value)){
			$value =  'null';
		}
		return $value;
	}
	
	/**
	 * field分析
	 * @access protected
	 * @param mixed $fields
	 * @return string
	 */
	protected function parseField($fields) {
		if(is_string($fields) && strpos($fields,',')) {
			$fields    = explode(',',$fields);
		}
		if(is_array($fields)) {
			// 完善数组方式传字段名的支持
			// 支持 'field1'=>'field2' 这样的字段别名定义
			$array   =  array();
			foreach ($fields as $key=>$field){
				if(!is_numeric($key))
					$array[] =  $this->parseKey($key).' AS '.$this->parseKey($field);
				else
					$array[] =  $this->parseKey($field);
			}
			$fieldsStr = implode(',', $array);
		}elseif(is_string($fields) && !empty($fields)) {
			$fieldsStr = $this->parseKey($fields);
		}else{
			$fieldsStr = '*';
		}
		//TODO 如果是查询全部字段，并且是join的方式，那么就把要查的表加个别名，以免字段被覆盖
		return $fieldsStr;
	}
	
	/**
	 * table分析
	 * @access protected
	 * @param mixed $table
	 * @return string
	 */
	protected function parseTable($tables) {
		if(is_array($tables)) {// 支持别名定义
			$array   =  array();
			foreach ($tables as $table=>$alias){
				if(!is_numeric($table))
					$array[] =  $this->parseKey($table).' '.$this->parseKey($alias);
				else
					$array[] =  $this->parseKey($table);
			}
			$tables  =  $array;
		}elseif(is_string($tables)){
			$tables  =  explode(',',$tables);
			array_walk($tables, array(&$this, 'parseKey'));
		}
		$tables = implode(',',$tables);
		return $tables;
	}
	
	/**
	 * where分析
	 * @access protected
	 * @param mixed $where
	 * @return string
	 */
	protected function parseWhere($where) {
		$whereStr = '';
		if(is_string($where)) {
			// 直接使用字符串条件
			$whereStr = $where;
		}else{ // 使用数组表达式
			$operate  = isset($where['_logic'])?strtoupper($where['_logic']):'';
			if(in_array($operate,array('AND','OR','XOR'))){
				// 定义逻辑运算规则 例如 OR XOR AND NOT
				$operate    =   ' '.$operate.' ';
				unset($where['_logic']);
			}else{
				// 默认进行 AND 运算
				$operate    =   ' AND ';
			}
			foreach ($where as $key=>$val){
				$whereStr .= '( ';
				if(is_numeric($key)){
					$key  = '_complex';
				}
				if(0===strpos($key,'_')) {
					// 解析特殊条件表达式
					$whereStr   .= $this->parseEasyWhere($key,$val);
				}else{
					// 查询字段的安全过滤
					if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){
						E('_EXPRESS_ERROR_:'.$key);
					}
					// 多条件支持
					$multi  = is_array($val) &&  isset($val['_multi']);
					$key    = trim($key);
					if(strpos($key,'|')) { // 支持 name|title|nickname 方式定义查询字段
						$array =  explode('|',$key);
						$str   =  array();
						foreach ($array as $m=>$k){
							$v =  $multi?$val[$m]:$val;
							$str[]   = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
						}
						$whereStr .= implode(' OR ',$str);
					}elseif(strpos($key,'&')){
						$array =  explode('&',$key);
						$str   =  array();
						foreach ($array as $m=>$k){
							$v =  $multi?$val[$m]:$val;
							$str[]   = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
						}
						$whereStr .= implode(' AND ',$str);
					}else{
						$whereStr .= $this->parseWhereItem($this->parseKey($key),$val);
					}
				}
				$whereStr .= ' )'.$operate;
			}
			$whereStr = substr($whereStr,0,-strlen($operate));
		}
		return empty($whereStr)?'':' WHERE '.$whereStr;
	}
	
	// where子单元分析
	protected function parseWhereItem($key,$val) {
		$whereStr = '';
		if(is_array($val)) {
			if(is_string($val[0])) {
				if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
					$name = md5($key);
					$name = $this->bindParam($name, $val[1]);
					$whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' :'.$name;
                }elseif('exp'==strtolower($val[0])){ // 使用表达式
					$whereStr .= ' ('.$key.' '.$val[1].') ';
				}elseif(preg_match('/IN/i',$val[0])){ // IN 运算
					if(is_string($val[1])){
						$val[1] = explode(',', $val[1]);
					}
                    $nameArr = array();
                    foreach ($val[1] as $k => $v) {
                        $name      = md5($key) . $k;
                        $name      = $this->bindParam($name, $v);
                        $nameArr[] = ':'.$name;
                    }
                    $whereStr .= $key . ' ' . strtoupper($val[0]) . ' (' . implode(',', $nameArr) . ')';
				}elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算
                    $data = is_string($val[1]) ? explode(',', $val[1]) : $val[1];

                    $name0 = md5($key) . '0';
                    $this->bindParam($name0, $data[0]);

                    $name1 = md5($key) . '1';
                    $this->bindParam($name1, $data[1]);

                    $whereStr .= ' (' . $key . ' ' . strtoupper($val[0]) . ' :' . $name0 . ' AND ' . $name1 . ' )';
				}else{
					E('_EXPRESS_ERROR_:'.$val[0]);
				}
			}else {
				E('_EXPRESS_ERROR_');
			}
		}else {
			$name = md5($key);
			$name = $this->bindParam($name, $val);
			$whereStr .= $key.' = :'.$name;
		}
		return $whereStr;
	}
	
	/**
	 * 特殊条件分析
	 * @access protected
	 * @param string $key
	 * @param mixed $val
	 * @return string
	 */
	protected function parseEasyWhere($key,$val) {
		$whereStr   = '';
		switch($key) {
			case '_string':
				// 字符串模式查询条件
				$whereStr = $val;
				break;
			case '_complex':
				// 复合查询条件
				$whereStr   =   is_string($val)? $val : substr($this->parseWhere($val),6);
				break;
			case '_query':
				// 字符串模式查询条件
				parse_str($val,$where);
				if(isset($where['_logic'])) {
					$op   =  ' '.strtoupper($where['_logic']).' ';
					unset($where['_logic']);
				}else{
					$op   =  ' AND ';
				}
				$array   =  array();
				foreach ($where as $field=>$data)
					$array[] = $this->parseKey($field).' = '.$this->parseValue($data);
				$whereStr   = implode($op,$array);
				break;
		}
		return $whereStr;
	}
	
	/**
	 * limit分析
	 * @access protected
	 * @param mixed $lmit
	 * @return string
	 */
	protected function parseLimit($limit) {
		return !empty($limit)?   ' LIMIT '.$limit.' ':'';
	}
	
	/**
	 * join分析
	 * @access protected
	 * @param array $join
	 * @return string
	 */
	protected function parseJoin($join) {
		$joinStr = '';
		if(!empty($join)) {
			$joinStr    =   ' '.implode(' ',$join).' ';
		}
		return $joinStr;
	}
	
	/**
	 * order分析
	 * @access protected
	 * @param mixed $order
	 * @return string
	 */
	protected function parseOrder($order) {
		if(is_array($order)) {
			$array   =  array();
			foreach ($order as $key=>$val){
				if(is_numeric($key)) {
					$array[] =  $this->parseKey($val);
				}else{
					$array[] =  $this->parseKey($key).' '.$val;
				}
			}
			$order   =  implode(',',$array);
		}
		return !empty($order)?  ' ORDER BY '.$order:'';
	}
	
	/**
	 * group分析
	 * @access protected
	 * @param mixed $group
	 * @return string
	 */
	protected function parseGroup($group) {
		return !empty($group)? ' GROUP BY '.$group:'';
	}
	
	/**
	 * having分析
	 * @access protected
	 * @param string $having
	 * @return string
	 */
	protected function parseHaving($having) {
		return  !empty($having)?   ' HAVING '.$having:'';
	}
	
	/**
	 * comment分析
	 * @access protected
	 * @param string $comment
	 * @return string
	 */
	protected function parseComment($comment) {
		return  !empty($comment)?   ' /* '.$comment.' */':'';
	}
	
	/**
	 * distinct分析
	 * @access protected
	 * @param mixed $distinct
	 * @return string
	 */
	protected function parseDistinct($distinct) {
		return !empty($distinct)?   ' DISTINCT ' :'';
	}
	
	/**
	 * union分析
	 * @access protected
	 * @param mixed $union
	 * @return string
	 */
	protected function parseUnion($union) {
		if(empty($union)) return '';
		if(isset($union['_all'])) {
			$str  =   'UNION ALL ';
			unset($union['_all']);
		}else{
			$str  =   'UNION ';
		}
		foreach ($union as $u){
			$sql[] = $str.(is_array($u)?$this->buildSelectSql($u):$u);
		}
		return implode(' ',$sql);
	}
	
	/**
	 * 替换SQL语句中表达式
	 * @access public
	 * @param array $options 表达式
	 * @return string
	 */
	public function parseSql($sql,$options=array()){
		$sql   = str_replace(
				array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%COMMENT%','%SET%'),
				array(
						$this->parseTable($options['table']),
						$this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
						$this->parseField(!empty($options['field'])?$options['field']:'*'),
						$this->parseJoin(!empty($options['join'])?$options['join']:''),
						$this->parseWhere(!empty($options['where'])?$options['where']:''),
						$this->parseGroup(!empty($options['group'])?$options['group']:''),
						$this->parseHaving(!empty($options['having'])?$options['having']:''),
						$this->parseOrder(!empty($options['order'])?$options['order']:''),
						$this->parseLimit(!empty($options['limit'])?$options['limit']:''),
						$this->parseUnion(!empty($options['union'])?$options['union']:''),
						$this->parseComment(!empty($options['comment'])?$options['comment']:''),
						$this->parseSet(isset($options['data']) && !empty($options['data'])?$options['data']:'')
				),$sql);
		return $sql;
	}
	
	/**
	 * 生成查询SQL
	 * @access public
	 * @param array $options 表达式
	 * @return string
	 */
	public function buildSelectSql($options=array()) {
		if(isset($options['page'])) {
			// 根据页数计算limit
			if(strpos($options['page'],',')) {
				list($page,$listRows) =  explode(',',$options['page']);
			}else{
				$page = $options['page'];
			}
			$page    =  $page?:1;
			$listRows=  isset($listRows)?$listRows:(is_numeric($options['limit'])?$options['limit']:20);
			$offset  =  $listRows*((int)$page-1);
			$options['limit'] =  $offset.','.$listRows;
		}
		if(C('DB_SQL_BUILD_CACHE')) { // SQL创建缓存
			$key    =  md5(serialize($options));
			$value  =  S($key);
			if(false !== $value) {
				return $value;
			}
		}

		$sql  =     $this->parseSql($this->selectSql,$options);
		$sql .=     $this->parseLock(isset($options['lock'])?$options['lock']:false);
		if(isset($key)) { // 写入SQL创建缓存
			S($key,$sql,array('expire'=>0,'length'=>C('DB_SQL_BUILD_LENGTH'),'queue'=>C('DB_SQL_BUILD_QUEUE')));
		}
		return $sql;
	}
	

	/**
	 * 生成更新SQL
	 * @access public
	 * @param array $options 表达式
	 * @return string
	 */
	public function buildUpdateSql($options=array()) {
		if($options['limit']){
			$options['limit'] = $options['limit']!=1?$options['limit']:1;
		}else{
			unset($options['limit']);
		}
		$sql  =     $this->parseSql($this->updateSql,$options);
		$sql .=     $this->parseLock(isset($options['lock'])?$options['lock']:false);
		return $sql;
	}
	
	
	/**
	 * 生成删除SQL
	 * @access public
	 * @param array $options 表达式
	 * @return string
	 */
	public function buildDeleteSql($options=array()) {
		if($options['limit']){
			$options['limit'] = $options['limit']!=1?$options['limit']:1;
		}else{
			unset($options['limit']);
		}
		$sql  =     $this->parseSql($this->deleteSql,$options);
		$sql .=     $this->parseLock(isset($options['lock'])?$options['lock']:false);
		return $sql;
	}
	
	/**
	 * 析构方法
	 * @access public
	 */
	public function __destruct() {
		// 释放查询
		if ($this->queryID){
			$this->free();
		}
		// 关闭连接
		$this->close();
	}
	
	// 关闭数据库 由驱动类定义
	public function close(){}
}